package com.tian.packapk

import com.android.build.api.dsl.BuildType
import com.android.build.api.variant.ApplicationAndroidComponentsExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import com.android.build.gradle.AbstractAppExtension
import org.gradle.api.Task

class PackagePlugin : Plugin<Project> {

    override fun apply(target: Project) {

        target.parent?.let { parent ->
            println("PackagePlugin  " + parent.name + "-----------,childProject ${parent.childProjects}")

            parent.tasks.forEach {
                println("PackagePlugin  taskName = " + it.name)
            }

            parent.childProjects.forEach { (_, project) ->
                val isAndroidLibrary = project.plugins.hasPlugin("com.android.library")
                println("PackagePlugin  " + project.name + "-----------, is isAndroidLibrary = $isAndroidLibrary")

                if (isAndroidLibrary) {
                    var ext: ApplicationAndroidComponentsExtension? = null
                    try {
                        ext = target.extensions.getByName("androidComponents") as ApplicationAndroidComponentsExtension
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                    if (ext != null) {
                        ext.finalizeDsl {
                            val bt = it.buildTypes.findByName("sit")
                            if (bt == null) {
                                println("PackagePlugin ---${target.name}  not has build type sit,so create it")
                                it.buildTypes.create("sit") {
                                    val debug: BuildType = it.buildTypes.findByName("debug") as BuildType
                                    initWith(debug)
                                }
                            }
                        }

                        ext.beforeVariants {
                            println("PackagePlugin beforeVariants ${project.name} ${it.name}")
                        }
                    }
                }
            }
        }



//        // 在配置结束时执行
//        target.afterEvaluate {
//            // 获取 "android" extension
//            val androidExt = extensions.findByName("android") as AbstractAppExtension
//            // 获取构建变体
//            androidExt.applicationVariants.forEach { appVariant ->
//                val flavorName = appVariant.flavorName
//                val buildTypeName = appVariant.buildType.name
//                // 获取构建遍体变体, [android 配置构建变体](https://developer.android.google.cn/studio/build/build-variants)
//                println("$flavorName $buildTypeName")
//
//                tasks.find { task ->
//                    task.name == "assemble${toUpperFirstChar(flavorName)}${toUpperFirstChar(buildTypeName)}"
//                }?.let { assembleTask ->
//                    // 输出目标task的名字
//                    println("打包task名字 " + assembleTask.name.orEmpty())
//                    appVariant.outputs.forEach { baseVariantOutput ->
//                        val apkPath1 = baseVariantOutput.outputFile.absolutePath
//                        println(apkPath1)
//                        // 对打包task (assembleTask进行取舍), 不能打debug环境的包
//                        if (!"debug".equals(buildTypeName, true)) {
//                            createPushMsgTask(this, apkPath1, flavorName, buildTypeName, assembleTask)
//                        }
//                    }
//                }
//            }
//        }
    }

    /**
     * 创建 打包并发送消息的task ，task属于 "oneKeyPackage"组，名字叫
     * @param apkPath
     * @param assembleTask
     * @return
     */
    private fun createPushMsgTask(
        project: Project,
        apkPath: String,
        flavorName: String,
        buildTypeName: String,
        assembleTask: Task
    ): Task {
        val taskName = "package" + toUpperFirstChar(flavorName) + toUpperFirstChar(buildTypeName) + "App"
        val task = project.tasks.create(taskName, PushMessageTask::class.java)
        task.apkPath = apkPath
        task.group = "oneKeyPackage"
        task.dependsOn(assembleTask)
        return task
    }

}